import {
	loginRequest
} from "./assets/js/index.js"
import {
	getCode
} from "./assets/js/login.js"

import api from './api/api.js'

// App.js
const app = {
	async onLaunch() {
		await this.login()
		await this.getTeam()
	},

	async login() {
		//获取本地token
		const token = wx.getStorageSync('WeTeamToken') || '';

		try {
			// 检查token是否过期
			const res = await loginRequest.post({
				url: '/isValid',
				header: {
					token // 确保这里使用的是正确的header字段
				}
			});
			console.log(res);

			// 登录
			if (token && res.ok) {
				const data = res.json()

				if (data.status === "Token is valid" && data.refreshedToken) {
					// 存储新token，例如存储在localStorage中
					wx.setStorageSync('WeTeamToken', data.refreshedToken);
					console.log('New token stored:', data.refreshedToken);
				} else {
					console.log('Token is still valid, no refresh needed.');
				}
			} else {
				await this.handlerLogin();
			}
		} catch (error) {
			console.error('检查token或处理登录时发生错误:', error);
			await this.handlerLogin(); // 如果发生错误，也执行登录
		}
	},


	// 登录的回调函数
	async handlerLogin() {
		console.log('handle')
		//获取code
		const code = await getCode();

		// 将code发给后端请求token
		const res = await loginRequest.post({
			url: "/login",
			data: {
				code
			}
		});
		console.log(res);

		// 保存token
		wx.setStorageSync('WeTeamToken', res.data);
	},

	async getTeam() {
		const choosenTeam = wx.getStorageSync('TheChoosenTeam');
		if (choosenTeam) {
			api.checkTeamIfExists(choosenTeam).then(res => {
				const exist = res.data.data
				if (!exist) {
					api.getJoinTeams().then(re => {
						const data = re.data.data
						if (data) {
							wx.setStorageSync('TheChoosenTeam', data[0])
						}
					})
				}
			})
		}
		if (!choosenTeam) {
			api.getJoinTeams().then(re => {
				const data = re.data.data
				if (data) {
					wx.setStorageSync('TheChoosenTeam', data[0])
				}
			})
		}
	}

};

export default app; // 使用默认导出